package com.company.chatRoom;

import com.company.utils.JSonUtil;
import com.company.utils.MyException;
import org.json.simple.JSONObject;

import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.Scanner;

/**
 * @Auther Xue
 * @Date 2021/4/28
 * @Version 1.0
 * @Desc    客户发送线程
 */
public class ClientSend implements Runnable {
    private Socket socket;
    private String username;
    private Map obj;
    //一个socket下的oos只能有一个
    private ObjectOutputStream oos;
    public ClientSend(Socket socket, String username) {
        this.socket = socket;
        this.username = username;
    }

    @Override
    public void run() {
        try {
            Scanner scanner = new Scanner(System.in);
            oos = Utils.getOOSBySocket(socket);
            obj = new HashMap();
            obj.put("type","login");
            obj.put("msg",username+"进入聊天");
            obj.put("user",username);
//            oos.writeObject(JSonUtil.obj2String(obj));
            oos.writeObject(obj);
            while (true){
                if(Utils.isServerClose(socket)){
                    socket.close();
                    System.out.println("断开连接");
                    break;
                }
                String str = scanner.nextLine();
                JSONObject obj = new JSONObject();
                obj.put("type","chat");
                obj.put("msg",str);
                obj.put("user",username);
//                oos.writeObject(JSonUtil.obj2String(obj));
                oos.writeObject(obj);
                oos.flush();
            }
        } catch (Exception e) {
            MyException.logExceptionMessage(e);
        }finally {
            try {
                socket.close();
                ChatClient.turnOffState();
                ChatClient.closeAllThread();
                ChatClient.reconnect();
            }catch (Exception e){
                MyException.logExceptionMessage(e);
            }
        }
    }

    public Socket getSocket() {
        return socket;
    }

    public void setSocket(Socket socket) {
        this.socket = socket;
    }

}
